package com.seafwg.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * @Author seafwg
 * @Date 2022/2/14 9:57 下午
 * @Version 1.0
 * @description ServletContextListener:servlet域是应用的最大域，ServletContextListener监听器监听了应用启动和销毁的方法
 */

public class ContextLoaderListener implements ServletContextListener {
    // 应用启动加载方
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //获取Servlet域对象
        ServletContext servletContext = servletContextEvent.getServletContext();
        //由于在web层中每个请求都要去通过加载配置类的方法创建app对象
        //在此创建app对象并保存到Servlet域中
        // ApplicationContext app = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        // servletContext.setAttribute("app", app);

        // 代码优化实现解藕
        // 在web.xml中配置全局参数,通过servletContext上下文获取参数
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
        // 存储在域中
        servletContext.setAttribute("app", app);
        System.out.println("ServletContextListener exe...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
